﻿// -----------------------------------------------------------------------
// <copyright file="InternalTransformerTaskHelper.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace Dhgms.TplHelper.Model.TaskHelper
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Dhgms.TplHelper.Controller.Task;
    using Dhgms.TplHelper.Model.Info;
    using Dhgms.TplHelper.Model.Info.JobResult;
    using Dhgms.TplHelper.Model.Info.TaskResult;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public abstract class InternalTransformerTaskHelper<TTaskResultClass, TTaskDataType> : BaseTaskHelper<TTaskResultClass>
        where TTaskResultClass : TaskResultBase, IReportableCount, ITaskDataResult<TTaskDataType>, new()
    {
        protected InternalTransformerTaskHelper(string name)
            : base(name)
        {
        }

        /// <summary>Entry point for doing the donkey work.</summary>
        /// <returns>The Execution Result.</returns>
        internal override TTaskResultClass Execute()
        {
            this.Logger.Info("Starting Task: " + this.Name);
            var result = new TTaskResultClass
            {
                Name = this.Name,
                Started = DateTime.Now,
            };

            var processResult = this.OnProcess();

            result.Data = processResult.DataResult;
            result.ReportableCount = processResult.ReportableCount;
            result.Finished = DateTime.Now;
            this.Logger.Info("Finished Task: " + this.Name);
            return result;
        }

        protected abstract DataRetrievalProcessorResult<TTaskDataType> OnProcess();

        /// <summary>
        /// Executes a job, adds the result to the TaskResultCollection and returns the internal data. Used to streamline some
        /// common functionality.
        /// </summary>
        /// <param name="taskResultCollection">
        /// The task result collection.
        /// </param>
        /// <typeparam name="TTaskDataType">
        /// Type for the Task Result Data Type.
        /// </typeparam>
        /// <returns>
        /// The task Result
        /// </returns>
        public TTaskDataType RunSynchronouslyAndGetData(TaskCollection taskResultCollection)
        {
            if (taskResultCollection == null)
            {
                throw new ArgumentNullException("taskResultCollection");
            }

            var taskResult = this.Execute();
            taskResultCollection.TaskResults.Add(taskResult);

            return taskResult.Data;
        }
    }
}
